<template>
  <div class="icon-config">
    <hzhy-data-table ref="dataTable" v-bind="tableConfig">
      <template slot="left-btn">
        <el-button type="primary" icon="el-icon-plus" plain @click="handleRowUpdate('add')">
          添加
        </el-button>
      </template>
    </hzhy-data-table>
    <common-dialog-form
      ref="commonDrawerForm"
      :visible.sync="visible"
      :title="drawerTitle"
      :content="formContent"
      :onConfirm="onConfirm"
    ></common-dialog-form>
  </div>
</template>

<script>
import CommonDialogForm from '@/components/common-dialog-form'
import CommonUploadFile from '@/components/common-upload-file'

import * as api from '@/const/api'

export default {
  title: '图标管理',
  name: 'ConfigureIconConfig',
  components: {
    CommonDialogForm,
  },
  data() {
    return {
      visible: false,
      currentRow: {},
      modelTree: [],
    }
  },
  computed: {
    // 编辑还是新增
    isEdit() {
      return !!this.currentRow.id
    },
    // 侧边栏表单标题
    drawerTitle() {
      return this.isEdit ? '编辑' : '新增'
    },
    tableConfig() {
      return {
        url: api.productIconPage,
        columns: [
          {
            label: '序号',
            type: 'index',
            prop: 'index',
          },
          {
            label: '图标名称',
            prop: 'name',
            minWidth: 120,
          },
          {
            label: '图标标题(中文)',
            prop: 'titleZh',
            minWidth: 120,
          },
          {
            label: '图标标题(英文)',
            prop: 'titleEn',
            minWidth: 120,
          },
          {
            label: '副标题(中文)',
            prop: 'subtitleZh',
            minWidth: 120,
          },
          {
            label: '副标题(英文)',
            prop: 'subtitleEn',
            minWidth: 120,
          },
          {
            label: '图标地址',
            prop: 'url',
            minWidth: 120,
            formatter: ({ url }) => {
              if (!url) {
                return ''
              }

              return (
                <img
                  src={url}
                  onClick={() => window.open(url)}
                  style="cursor: pointer;max-width: 60px;height:32px;display: block;"
                />
              )
            },
          },
          {
            label: '操作',
            prop: 'operation',
            width: 160,
            fixed: 'right',
            setBtns: (row) => {
              const btns = [
                {
                  label: '编辑',
                  handler: () => {
                    this.handleRowUpdate('edit', row)
                  },
                },
                {
                  label: '删除',
                  className: 'red',
                  handler: () => {
                    this.handleRowDelete(row)
                  },
                },
              ]
              return this.$ac.operationAccess(btns)
            },
          },
        ],
        searchForm: [
          {
            $type: 'input',
            $id: 'name',
            label: '图标名称',
            $el: {
              clearable: true,
              placeholder: '请输入',
            },
          },
        ],
      }
    },
    formContent() {
      return [
        {
          $id: 'name',
          $type: 'input',
          label: '图标名称',
          $el: {
            placeholder: '请输入图标名称',
            clearable: true,
            maxlength: 50,
            showWordLimit: true,
          },
          rules: [{ required: true, message: '请输入图标名称', trigger: 'change' }],
        },
        {
          component: CommonUploadFile,
          $id: 'url',
          label: '图标地址',
          $el: {
            max: 1,
            accept: '.svg,.jpg,.jpeg,.png',
            tips: '图片最佳尺寸：60 X 60',
          },
          inputFormat: ({ url }) => {
            if (!url) {
              return []
            }
            const result = []
            url.split(',').forEach((item) => {
              result.push({
                name: item,
                response: item,
              })
            })
            return result
          },
          outputFormat: (val) => {
            if (!val || !val.length) {
              return
            }
            return val.map(({ response }) => response).join(',')
          },
          rules: [
            {
              required: true,
              message: '请输入图标地址',
              validator: (rule, value, callback) => {
                if (value && value.length) {
                  callback()
                } else {
                  return callback(new Error('请输入图标地址'))
                }
              },
            },
          ],
        },
        {
          $id: 'titleZh',
          $type: 'input',
          label: '标题(中文)',
          $el: {
            placeholder: '请输入标题(中文)',
            clearable: true,
            maxlength: 50,
            showWordLimit: true,
          },
        },
        {
          $id: 'titleEn',
          $type: 'input',
          label: '标题(英文)',
          $el: {
            placeholder: '请输入标题(英文)',
            clearable: true,
            maxlength: 50,
            showWordLimit: true,
          },
        },
        {
          $id: 'subtitleZh',
          $type: 'input',
          label: '副标题(中文)',
          $el: {
            placeholder: '请输入副标题(中文)',
            clearable: true,
            maxlength: 50,
            showWordLimit: true,
          },
        },
        {
          $id: 'subtitleEn',
          $type: 'input',
          label: '副标题(英文)',
          $el: {
            placeholder: '请输入副标题(英文)',
            clearable: true,
            maxlength: 50,
            showWordLimit: true,
          },
        },
      ]
    },
  },
  methods: {
    // 侧边栏form确认回调
    async onConfirm(data) {
      try {
        const params = {
          ...data,
        }
        // 编辑需要加上id参数
        if (this.isEdit) {
          params.id = this.currentRow.id
        }

        let res = ''

        if (this.isEdit) {
          res = await this.$axios.$put(api.productIcon, params)
        } else {
          res = await this.$axios.$post(api.productIcon, params)
        }

        const { code, msg } = res
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }

        this.$message.success('操作成功')
        this.$refs.dataTable.goPage()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 打开侧边栏form弹层
    handleRowUpdate(type, row) {
      this.visible = true
      if (type === 'edit') {
        this.currentRow = row
        this.$refs.commonDrawerForm.updateForm(row)
      } else {
        this.currentRow = {}
      }
    },
    async handleRowDelete(row) {
      let loading = ''
      try {
        const isFlag = await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        if (isFlag !== 'confirm') {
          return
        }
        loading = this.$loading({
          text: 'Loading',
          spinner: 'el-icon-loading',
        })
        const { code, msg } = await this.$axios.$delete(api.deleteProductIcon(row.id))
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.$message.success('操作成功')
        this.$refs.dataTable.goPage()
      } catch (err) {
        err.message && this.$message.error(err.message)
      } finally {
        loading && loading.close()
      }
    },
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.factoryName.includes(value)
    },
  },
}
</script>

<style lang="less" scoped>
@import '~assets/var';

.product {
  width: 100%;
  height: 100%;
  display: flex;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    zoom: 0.8;
  }

  .a-side {
    flex: 0 0 280px;
    border-right: 1px solid #e4e8f3;
    padding: 15px 10px 0 15px;

    .a-side-title {
      display: flex;
      align-items: center;

      &::before {
        display: block;
        content: ' ';
        width: 4px;
        height: 12px;
        background-color: #575962;
        border-radius: 3px;
        margin-right: 6px;
      }
    }

    .a-side-add {
      cursor: pointer;
    }

    .a-side-input {
      margin: 15px 0;
    }

    :deep(.el-tree) {
      height: calc(100% - 80px);
      overflow: auto;

      .custom-tree-node {
        display: flex;
        flex: 1;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;

        i {
          color: @breadcrumb-color;
          font-size: 14px;
        }

        .node-label {
          flex: 1;

          &.active {
            color: #435fba;
            font-weight: bold;
          }
        }
      }
    }
  }

  .content {
    flex: 1;
    padding-left: 20px;
    overflow: hidden;

    .scroll {
      width: 100%;
      height: 100%;
      overflow: auto;
    }
  }
}
</style>
